package cn.bocai.pc.web.controller;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.bocai.pc.model.BcLinktble;
import cn.bocai.pc.model.BcLinktype;
import cn.bocai.pc.model.BcThumpic;
import cn.bocai.pc.model.Variable;
import cn.bocai.pc.service.BcCollectService;
import cn.bocai.pc.service.BcLinktbleService;
import cn.bocai.pc.service.BcLinktypeService;
import cn.bocai.pc.service.BcPictureService;
import cn.bocai.pc.service.BcThumpicService;
import cn.bocai.pc.service.VariableService;
import cn.bocai.pc.util.FMutil;
import cn.bocai.pc.util.RandomUtils;
import cn.bocai.pc.util.UUIDUtils;

/**
 * 
 * @author 99fu
 *
 */
@Controller
@RequestMapping("/baSkip")
public class BaSkipPageController {
	@Autowired
	private BcThumpicService bcThumpicService;
	@Autowired
	private BcLinktbleService bcLinktbleService;
	@Autowired
	private BcLinktypeService bcLinktypeService;
	@Autowired
	private BcCollectService bcCollectService;
	@Autowired
	private BcPictureService bcPictureService;
	@Autowired
	private VariableService variableService;
	//进入框架
	@RequestMapping("/ifram.do")
	public String ifram(){
		
		return "baPage/ifram";
	}
	
	//进入框架主页
	@RequestMapping("/main.do")
	public String main(){
		return "baPage/main";
	}
	//框架顶部
	@RequestMapping("/top.do")
	public String top(){
		return "baPage/top";
	}
	//进入框架左侧
	@RequestMapping("/left.do")
	public String left(){
		return "baPage/left";
	}
	
	
	//首页
	@RequestMapping("/picCut.do")
	public String picCut(){
		return "baPage/picCut";
	}
	
	@RequestMapping("/bottomLink.do")
	public String bottomLink(){
		return "baPage/bottomLink";
	}
	
	//批量操作
	@RequestMapping("/batchOperate.do")
	public String batchOperate(){
		return "baPage/configuration/batchOperate";
	}
	
	//生成静态页面
	@RequestMapping("/staticHtml.do")
	public String staticHtml(){
		return "baPage/static/staticHtml";
	}
	
	//首页底部数据
	@RequestMapping("/botPopLink/{botPopLink}.do")
	public String botPopLink(HttpServletRequest request,HttpServletResponse response,Model m,String type,@PathVariable String botPopLink){
		if("botPopLinkType".endsWith(botPopLink)){
			//类型名称
			linktype(request,m,type);
		}else{
			//类型数据
			linktable(request,response,m,type);
		}
		m.addAttribute("botPopLink", botPopLink);//用于判断类型
		return "baPage/homePage/botPopLink";
	}
	
	//首页大家都在看
		@RequestMapping("/botLookLink/{botLookLink}.do")
		public String botLookLink(HttpServletRequest request,HttpServletResponse response,Model m,String type,@PathVariable String botLookLink){
			if("botLookLinkType".endsWith(botLookLink)){
				//类型名称
				linktype(request,m,type);
			}else{
				//类型数据
				linktable(request,response,m,type);
			}
			m.addAttribute("botPopLink", botLookLink);//用于判断类型
			return "baPage/homePage/linkLook";
		}
		//彩票、真人、娱乐、体育
		@RequestMapping("/botFourLink/{botFourLink}.do")
		public String botFourLink(HttpServletRequest request,HttpServletResponse response,Model m,String type,@PathVariable String botFourLink){
			if("botFourLinkType".endsWith(botFourLink)){
				//类型名称
				linktype(request,m,type);
			}else{
				//类型数据
				linktable(request,response,m,type);
			}
			m.addAttribute("botPopLink", botFourLink);//用于判断类型
			return "baPage/homePage/linkFour";
		}
	
	//删除类型单条数据
	@RequestMapping("/delectTypeOne.do")
	public void delectTypeOne(HttpServletRequest request,HttpServletResponse response,String id,String linkType){
		int returndata = bcLinktypeService.deleteByPrimaryKey(id);//删除类型中的数据
		int deleteByType=100;
		if(1==returndata){
		  deleteByType = bcLinktbleService.deleteByType(id);
		}
		try {
			response.getWriter().print(deleteByType);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	//删除类型数据单条数据
		@RequestMapping("/delectTableOne.do")
		public void delectTableOne(HttpServletRequest request,HttpServletResponse response,String id){
			int returndata = bcLinktbleService.deleteByPrimaryKey(id);//删除类型中的数据
			try {
				response.getWriter().print(returndata);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		//批量删除数据
		@RequestMapping("/delectAllTable.do")
		public void delectAllTable(HttpServletRequest request,HttpServletResponse response,String sum){
			String[] id = request.getParameter("sum").split(",");
			int returndata=0;
			for(int i=0;i<id.length;i++){
				returndata = bcLinktbleService.deleteByPrimaryKey(id[i]);//删除类型中的数据
			}
			try {
				response.getWriter().print("succeed");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	
		//批量删除数据
		@RequestMapping("/delectAllType.do")
		public void delectAllType(HttpServletRequest request,HttpServletResponse response,String sum){
			String[] id = request.getParameter("sum").split(",");
			for(int i=0;i<id.length;i++){
				/* String[] ids=id[i].split("_");*/
				 int returndata = bcLinktypeService.deleteByPrimaryKey(id[i]);//删除类型中的数据
				 int deleteByType=100;
				 if(1==returndata){
					  deleteByType = bcLinktbleService.deleteByType(id[i]);
				  }
			}
			try {
				response.getWriter().print("succeed");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}	
		
		
		//编辑修改
		@RequestMapping("/updateTyTa.do")
		public void updateTyTa(HttpServletRequest request,HttpServletResponse response,BcLinktype reType,BcLinktble reTable){
			 String typeMode = request.getParameter("typeMode");//获取数量类型名称
			 String part = request.getParameter("part");//获取判断
			 String id = request.getParameter("thisid");//获取id
			 String editVal = request.getParameter("thisvalue");//获取值
			 int data=0;
			 String linkTypes="null";
			 if("type".equals(part)){
				 reType.setId(id);
				 boolean variable=true;
				if(("linkType").equals(typeMode)){
					for(int i=0;i<editVal.length();i++){  
			    		 boolean matches = editVal.substring(i,i+1).matches("[\\u4e00-\\u9fa5]+");
			    		 if(matches){
			    			 variable=false;
			    			 break;  
			    		 }
			    	  }
					reType.setLinkType(editVal);
					linkTypes=editVal;//强值赋值给类型
				}
				if(variable){
					if(("linkTypename").equals(typeMode)){
						reType.setLinkTypename(editVal);				
									}
					if(("remarks1").equals(typeMode)){
						reType.setRemarks1(Integer.parseInt(editVal));
					}
					int updatype = bcLinktypeService.updateByPrimaryKeySelective(reType);
					if(!"null".equals(linkTypes) && 1==updatype){
						HashMap<String, Object> map = new HashMap<String, Object>();
						map.put("fid", id);
						map.put("name", editVal);
						int updateLinkType = bcLinktbleService.updateLinkType(map);//修改table中的类型名称
					}
					data=updatype;
				}else{
					data=100;
				}
				
			 }else {
				reTable.setId(id);
				if(("linkName").equals(typeMode)){
					reTable.setLinkName(editVal);				
				}
				if(("linkAddress").equals(typeMode)){
					reTable.setLinkAddress(editVal);
				}
				if(("linkSort").equals(typeMode)){
					reTable.setLinkSort(Integer.parseInt(editVal));
				}
				if(("skipAddress").equals(typeMode)){
					reTable.setSkipAddress(editVal);
				}
				if(("weight").equals(typeMode)){
					reTable.setWeight(editVal);
				}
				
				int updatable = bcLinktbleService.updateByPrimaryKeySelective(reTable);
				data=updatable;
			}
			 
			 
			try {
				response.getWriter().print(data);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}		
		
		
	// 生成底部链接模板
	@RequestMapping("/creatFtl.do")
	public void creatFtl(HttpServletRequest request,HttpServletResponse response) {
			String selectLinktble = bcLinktbleService.selectLinktble("1");//生成底部外部链接模板
			
			//生成模板首页
			String pers= homePage(request,response);
			
			try {
				response.getWriter().print(selectLinktble);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	
	// 生成大家来看模板
		@RequestMapping("/FtlLookFour.do")
		public void FtlLookFour(HttpServletRequest request,HttpServletResponse response) {
				String selectLinktble = bcLinktbleService.FtlLookFour();//根据类型查询出所有数据
				
				try {
					response.getWriter().print(selectLinktble);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		//校验类型名称是否存在
		@RequestMapping("/checkoutTypeName.do")
		public void checkoutTypeName(HttpServletRequest request,HttpServletResponse response,String type){
			
			 String name = request.getParameter("name");
			 boolean variable=true;
			   for(int i=0;i<name.length();i++){  
		    		 boolean matches = name.substring(i,i+1).matches("[\\u4e00-\\u9fa5]+");//监测是否有中文
		    		 if(matches){
		    			 variable=false;
		    			 break;  
		    		 }
		    	  }
			 if(variable){
				 Map<String, Object> map = new HashMap<String, Object>();
				 map.put("name",name);
				 map.put("type",type);
				 BcLinktype checkoutTypeName = bcLinktypeService.checkoutTypeName(map);
				 String data="0";
				 if(null!=checkoutTypeName){
					 data="1";
				 }
					try {
						response.getWriter().print(data);
					} catch (IOException e) {
						e.printStackTrace();
					} 
			 }else{
				 try {
					response.getWriter().print("100");
				} catch (IOException e) {
					e.printStackTrace();
				}
			 }
		}		
			
		
	/**
	 * 类型数据页面分页
	 * @time 2015/08/12
	 */
	public void linktype(HttpServletRequest request,Model m,String type){
		      String _ps = request.getParameter("pageSize");
		        //1:定义每页显示多少行记录
				int pageSize = 12;
				 //将获取到前台的用户要求的显示的第几页数据转化为整型类型数据
				if(_ps!=null && !_ps.trim().equals("")){
					try{
						pageSize = Integer.parseInt(_ps);
					}catch(Exception e){
						//不处理
					}
				}
				
				//2:获取用户要求显示第几页
				String _cp = request.getParameter("currentPageNumber");
				//默认等于第一页
				int currentPage = 1;
		         //将获取到前台的用户要求的显示的第几页数据转化为整型类型数据
				if(_cp!=null && !_cp.trim().equals("")){
					try{
						currentPage = Integer.parseInt(_cp);
					}catch(Exception e){
						//不处理
					}
				}
				try{
					//执行查询出全部数据的总行数
					int rowCount = bcLinktypeService.typeLineNumber(type);
					//4:计算一共分多少页
					int pageCount = rowCount/pageSize+(rowCount%pageSize==0?0:1);
					//判断当前页面要求页数是否已经大于pageCount（总页数）最大页数，如果大于就拿总页数否则就拿页面要求的
					currentPage=(currentPage>pageCount?pageCount:currentPage);
					//判断
			     	currentPage=(currentPage<=0?1:currentPage);
					//5:计算从哪一行开始查询
					int start = (currentPage-1)*pageSize;
					
					//6:查询出指定行数的数据
					 Map<String, Object> map = new HashMap<String, Object>();
					 map.put("start",start);
					 map.put("pageSize",pageSize);
					 map.put("type",type);
					 List<BcLinktype> datas = bcLinktypeService.typePaging(map);
					 
					//封装数据将传到前台数据
					 m.addAttribute("Tydatas", datas);//查询出的数据
					 m.addAttribute("TypageCount",pageCount);//一个分多少页
					 m.addAttribute("TycurrentPage", currentPage);//当前页数
					 m.addAttribute("TyrowCount", rowCount);//一共多少条数据
					 m.addAttribute("TypageSize", pageSize);//每页显示的条数
					 
					//以下计算开始显示的页码和结束显示的页码
						int showCount = 10;  //页面显示多少个页码
						int showStart = 0;   //
						int showEnd = 0;     //
						//如果总页码还不够15页
						if(pageCount<=showCount){
							showStart=1;
							showEnd=pageCount;//那么结束页面就等于总页码
						}else{//分页显示页码
							if(currentPage<=(showCount/2)){
								showStart=1;
								showEnd=showCount;
							}else{
								showStart=currentPage-(showCount/2-1);
								showEnd=showStart+(showCount-1);
							}
							//如果showEnd已经超出总页面
							if(showEnd>=pageCount){ //最后的页面大于等于总页码
								showEnd=pageCount;
								showStart=showEnd-(showCount-1);
							}
						}
						m.addAttribute("TyshowStart",showStart);
						m.addAttribute("TyshowEnd",showEnd);

				}catch(Exception e){
					throw new RuntimeException(e);
				}
	}
	
	
	
	/**
	 * 类型数据页面分页
	 * @time 2015/08/12
	 */
	public void linktable(HttpServletRequest request,HttpServletResponse response,Model m,String type){
		
		    String baUrl=variableService.selectVariable("BA_URL");//获取图片服务器的地址
		    //查询出类型中的所有数据返回生成下拉列表
			List<BcLinktype> selectAll = bcLinktypeService.selectAll(type);
			m.addAttribute("selectAllty", selectAll);//类型中所有数据
			m.addAttribute("baUrl", baUrl);//传值前台
			
		   //获取前段传输过来的id值
		    String typeId= request.getParameter("typeData");
		    		
		   //查询友情链接类型的第一个数据（默认的）
			String linkTypeId=null;
			String linkTypename=null;
				if(selectAll.size()>0){
					linkTypeId= selectAll.get(0).getId();
					linkTypename = selectAll.get(0).getLinkTypename();
				}
				//将获取到前台的用户要求的显示的第几页数据转化为整型类型数据
				if(typeId!=null && !typeId.trim().equals("")){
					try{
						linkTypeId = typeId;
						linkTypename=bcLinktypeService.selectBylinktypeId(typeId).getLinkTypename();//查询出类型的中文名称
					}catch(Exception e){
						//不处理
					}
				}
				
				String linkType= bcLinktypeService.selectBylinktypeId(linkTypeId).getLinkType();//查询出类型;
				
				m.addAttribute("selectTypeId", linkTypeId);//获取类型数据id
				m.addAttribute("selectType", linkType);//获取类型数据
				m.addAttribute("selectName", linkTypename);//第一个的名称
				
			      String _ps = request.getParameter("pageSize");
			        //1:定义每页显示多少行记录
					int pageSize = 12;
					 //将获取到前台的用户要求的显示的第几页数据转化为整型类型数据
					if(_ps!=null && !_ps.trim().equals("")){
						try{
							pageSize = Integer.parseInt(_ps);
						}catch(Exception e){
							//不处理
						}
					}
					
					//2:获取用户要求显示第几页
					String _cp = request.getParameter("currentPageNumber");
					//默认等于第一页
					int currentPage = 1;
			         //将获取到前台的用户要求的显示的第几页数据转化为整型类型数据
					if(_cp!=null && !_cp.trim().equals("")){
						try{
							currentPage = Integer.parseInt(_cp);
						}catch(Exception e){
							//不处理
						}
					}
					try{
						Map<String, Object> map = new HashMap<String, Object>();
						 map.put("linktypeId",linkTypeId);
						 map.put("type",type);
						//执行查询出全部数据的总行数
						int rowCount = bcLinktbleService.tableLineNumber(map);
						//4:计算一共分多少页
						int pageCount = rowCount/pageSize+(rowCount%pageSize==0?0:1);
						//判断当前页面要求页数是否已经大于pageCount（总页数）最大页数，如果大于就拿总页数否则就拿页面要求的
						currentPage=(currentPage>pageCount?pageCount:currentPage);
						//判断
				     	currentPage=(currentPage<=0?1:currentPage);
						//5:计算从哪一行开始查询
						int start = (currentPage-1)*pageSize;
						
						//6:查询出指定行数的数据
						 
						 map.put("start",start);
						 map.put("pageSize",pageSize);
						 List<BcLinktble> datas = bcLinktbleService.tablePaging(map);
						 
						//封装数据将传到前台数据
						 m.addAttribute("Tadatas", datas);//查询出的数据
						 m.addAttribute("TapageCount",pageCount);//一个分多少页
						 m.addAttribute("TacurrentPage", currentPage);//当前页数
						 m.addAttribute("TarowCount", rowCount);//一共多少条数据
						 m.addAttribute("TapageSize", pageSize);//每页显示的条数
						 
						//以下计算开始显示的页码和结束显示的页码
							int showCount = 10;  //页面显示多少个页码
							int showStart = 0;   //
							int showEnd = 0;     //
							//如果总页码还不够15页
							if(pageCount<=showCount){
								showStart=1;
								showEnd=pageCount;//那么结束页面就等于总页码
							}else{//分页显示页码
								if(currentPage<=(showCount/2)){
									showStart=1;
									showEnd=showCount;
								}else{
									showStart=currentPage-(showCount/2-1);
									showEnd=showStart+(showCount-1);
								}
								//如果showEnd已经超出总页面
								if(showEnd>=pageCount){ //最后的页面大于等于总页码
									showEnd=pageCount;
									showStart=showEnd-(showCount-1);
								}
							}
							m.addAttribute("TashowStart",showStart);
							m.addAttribute("TashowEnd",showEnd);
	
					}catch(Exception e){
						throw new RuntimeException(e);
					}
	}
	
	
	//彩色图库
	@RequestMapping("/colQuery.do")
	public String colQuery(){
		return "baPage/col/colQuery";
	}
	
	//黑白图库
	@RequestMapping("/blaQuery.do")
	public String blaQuery(){
		return "baPage/black/blaQuery";
	}
	
	//彩色图扫描
	@RequestMapping("/colScan.do")
	public String colUplod(Model m){
		String varHtmlUrl = variableService.selectVariable("HTML_URL");//http://localhost:8080/pc-portal
		m.addAttribute("path",varHtmlUrl);
		return "baPage/col/colScan";
	}
	
	
	//黑白图扫描
	@RequestMapping("/blaScan.do")
	public String blaUplod(Model m){
		String varHtmlUrl = variableService.selectVariable("HTML_URL");//http://localhost:8080/pc-portal
		m.addAttribute("path",varHtmlUrl);
		return "baPage/black/blaScan";
	}
	//跳转文件夹监测
	@RequestMapping("/monitorFileState.do")
	public String monitorFileState(){
			
		return "baPage/monitorFile/monitorFileState";
	}
	//查询出所有略缩图信息
	@RequestMapping("/thumPic.do")
	public String thumPic(HttpServletRequest request, HttpServletResponse response,Model m){
		thumPicPaging(request,m);
		return "baPage/thumFile/thumPic";
	}
	
	//年份修改跳转
	@RequestMapping("/alterYear.do")
	public String alterYear(HttpServletRequest request, HttpServletResponse response,Model m){
		Variable newYear=variableService.selectYear("year");
		m.addAttribute("newYear",newYear);
		return "baPage/alterYear/alterYear";
	}

	// 修改数据库中年份信息
	@RequestMapping("/newYear.do")
	public void newYear(HttpServletRequest request,
			HttpServletResponse response, Model m, Variable record)
			throws IOException {
		String year = request.getParameter("year");
		String id = request.getParameter("id");

		record.setVariableval(year);
		record.setId(id);

		int nowYear = variableService.updateByPrimaryKeySelective(record);
		response.getWriter().print(nowYear);
	}

	// 友情链接新增数据类型
	@RequestMapping("/addTypeData.do")
	public void addTypeData(HttpServletRequest request,
			HttpServletResponse response, BcLinktype reType) throws IOException {
		String addType = request.getParameter("addType");
		String addTypename = request.getParameter("addTypename");
		String addTypeSort = request.getParameter("addTypeSort");
		addPublicData(response, reType, addType, addTypename, addTypeSort, "1");
	}

	// 大家都在看新增数据类型
	@RequestMapping("/addLookData.do")
	public void addLookData(HttpServletRequest request,
			HttpServletResponse response, BcLinktype reType) throws IOException {
		String addType = request.getParameter("addLook");
		String addTypename = request.getParameter("addLookname");
		String addTypeSort = request.getParameter("addLookSort");
		addPublicData(response, reType, addType, addTypename, addTypeSort, "2");
	}
	// 体育、彩票、真人、游戏
	@RequestMapping("/addFourData.do")
	public void addFourData(HttpServletRequest request,
			HttpServletResponse response, BcLinktype reType) throws IOException {
		String addType = request.getParameter("addFour");
		String addTypename = request.getParameter("addFourname");
		String addTypeSort = request.getParameter("addFourSort");
		addPublicData(response, reType, addType, addTypename, addTypeSort, "3");
	}
	// 公共方法
	public void addPublicData(HttpServletResponse response, BcLinktype reType,String addType, String addTypename, String addTypeSort, String Type)
			throws IOException {
		int parseInt = Integer.parseInt(addTypeSort);
		boolean variable = true;
		for (int i = 0; i < addType.length(); i++) {
			boolean matches = addType.substring(i, i + 1).matches(
					"[\\u4e00-\\u9fa5]+");
			if (matches) {
				variable = false;
				break;
			}
		}
		if (variable) {
			reType.setId(UUIDUtils.getUUID32());
			reType.setLinkType(addType);
			reType.setLinkTypename(addTypename);
			reType.setRemarks1(parseInt);
			reType.setType(Type);
			int insertSelective = bcLinktypeService.insert(reType);
			response.getWriter().print(insertSelective);
		} else {
			response.getWriter().print("100");
		}
	}
		//友情链接新增类型数据
		@RequestMapping("/addTableData.do")
		public void addTableData(HttpServletRequest request, HttpServletResponse response,BcLinktble reTable) throws IOException{
			String id = request.getParameter("addTableId");

			String addTableName = request.getParameter("addTableName");
			String addTableUrlname = request.getParameter("addTableUrlname");
			/*String addTableSkip = request.getParameter("addTableSkip");*/
			String addTableUrl = request.getParameter("addTableUrl");
			String addTableSort = request.getParameter("addTableSort");
			int parseInt = Integer.parseInt(addTableSort);
			
			//获取底部友好链接的存放磁盘
			String linkUrl=variableService.selectVariable("LINK_UEL");
			
			reTable.setId(UUIDUtils.getUUID32());
			reTable.setLinktypeid(id);
			reTable.setLinkName(addTableUrlname);
			reTable.setSkipAddress(linkUrl+"/"+addTableName+"_"+RandomUtils.game(4)+".html");
			reTable.setLinkAddress(addTableUrl);
			reTable.setLinkSort(parseInt);
			reTable.setLinktypename(addTableName);
			reTable.setLinktype("1");
			int insert = bcLinktbleService.insert(reTable);
			response.getWriter().print(insert);
		}
		
		
		//大家都在看类型数据
		@RequestMapping("/addLookTabData.do")
		public void addLookTabData(HttpServletRequest request, HttpServletResponse response,BcLinktble reTable) throws IOException{
			String id = request.getParameter("addLookTabId");

			String addTableName = request.getParameter("addLookTabName");
			String addTableUrlname = request.getParameter("addLookTabUrlname");
			/*String addTableSkip = request.getParameter("addTableSkip");*/
			String addTableUrl = request.getParameter("addLookTabUrl");
			String addTabColour = request.getParameter("upisRecommend");
			
			String addTableSort = request.getParameter("addLookTabSort");
			int parseInt = Integer.parseInt(addTableSort);
			
			//获取当前最新年份
			String year=variableService.selectVariable("year");
			
			reTable.setId(UUIDUtils.getUUID32());
			reTable.setLinktypeid(id);
			reTable.setLinkName(addTableUrlname);
			reTable.setSkipAddress("/"+year+"/"+addTabColour+"/"+addTableUrl+".html");
			reTable.setWeight(addTableUrl);
			reTable.setLinkSort(parseInt);
			reTable.setLinktypename(addTableName);
			reTable.setLinktype("2");
			int insert = bcLinktbleService.insert(reTable);
			response.getWriter().print(insert);
		}

// 游戏、真人等类型数据
	
		@RequestMapping("/addFourTabData.do")
		public void addFourTabData(HttpServletRequest request, HttpServletResponse response,BcLinktble reTable) throws IOException{
			String id = request.getParameter("addFourTabId");

			String addTableName = request.getParameter("addFourTabName");
			String addTableUrlname = request.getParameter("addFourTabUrlname");
			String addTableUrl = request.getParameter("addFourTabUrl");

			String addTableSort = request.getParameter("addFourTabSort");
			int parseInt = Integer.parseInt(addTableSort);

			String imgsaddress = request.getParameter("imgsFouraddress");

			reTable.setId(UUIDUtils.getUUID32());
			reTable.setLinktypeid(id);
			reTable.setLinkName(addTableUrlname);
			reTable.setSkipAddress(imgsaddress);
			reTable.setLinkAddress(addTableUrl);
			reTable.setLinkSort(parseInt);
			reTable.setLinktypename(addTableName);
			reTable.setLinktype("3");
			int insert = bcLinktbleService.insert(reTable);
			response.getWriter().print(insert);
		}
	/**
	 * 搜索分页
	 * @time 2015/07/07
	 */
	public void thumPicPaging(HttpServletRequest request,Model m){
		    //http://localhost:8081
		    String PicUrl = variableService.selectVariable("PIC_URL");
		    
		    String _cs = request.getParameter("colour");
	        //1:获取右上角的选择条件
			String colour = null;//默认条件是
			 //将获取到前台的用户要求的图片类型进行赋值
			if(_cs!=null && !_cs.trim().equals("")){
				try{
					colour =_cs;
				}catch(Exception e){
					//不处理
				}
			}
		    
		    String method = request.getMethod();//获取请求的类型
		    String parKeyword = request.getParameter("queryValue");//获取搜索框传输过来的值
		    
		    if(parKeyword!=null && !parKeyword.trim().equals("")){
		    	m.addAttribute("retColour", _cs);//将颜色的值返回
		    	 //如果是post请求是不需要进行中文转码的，但是如果是get请求那就需要中文转码了
		    	if("GET".equalsIgnoreCase(method)){
		    		try {
						parKeyword=new String (parKeyword.getBytes("ISO-8859-1"),"utf-8");
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}//中文get形式传输需要转码
		    	}
		    }
		   
		    
		      String _ps = request.getParameter("pageSize");
		        //1:定义每页显示多少行记录
				int pageSize =15;
				 //将获取到前台的用户要求的显示的第几页数据转化为整型类型数据
				if(_ps!=null && !_ps.trim().equals("")){
					try{
						pageSize = Integer.parseInt(_ps);
					}catch(Exception e){
						//不处理
					}
				}
				//2:获取用户要求显示第几页
				String _cp = request.getParameter("currentPageNumber");
				//默认等于第一页
				int currentPage = 1;
		         //将获取到前台的用户要求的显示的第几页数据转化为整型类型数据
				if(_cp!=null && !_cp.trim().equals("")){
					try{
						currentPage = Integer.parseInt(_cp);
					}catch(Exception e){
						//不处理
					}
				}
				try{
					//查询出一共多少条数
					int rowCount=0;
					if(parKeyword!=null && !parKeyword.trim().equals("")){
						Map<String,Object> searCount = new HashMap<String,Object>();
						searCount.put("parKeyword",parKeyword);
						searCount.put("parType",colour);
						rowCount = bcThumpicService.searAllRow(searCount);//查询搜索的时候的值
					}else{
						rowCount = bcThumpicService.searRowAll(colour);
					}
					//4:计算一共分多少页
					int pageCount = rowCount/pageSize+(rowCount%pageSize==0?0:1);
					//判断当前页面要求页数是否已经大于pageCount（总页数）最大页数，如果大于就拿总页数否则就拿页面要求的
					currentPage=(currentPage>pageCount?pageCount:currentPage);
					//判断
			     	currentPage=(currentPage<=0?1:currentPage);
					//5:计算从哪一行开始查询
					int start = (currentPage-1)*pageSize;
					//6:查询出指定行数的数据
					Map<String,Object> searMap = new HashMap<String,Object>();
				     searMap.put("start",start);
				     searMap.put("pageSize",pageSize);
				     searMap.put("colour",colour);
				     
				     List<BcThumpic> searchList=null;
						if(parKeyword!=null && !parKeyword.trim().equals("")){
							searMap.put("parKeyword",parKeyword);
						     searchList = bcThumpicService.searDataPic(searMap);//查询搜索的分页
						}else{
							searchList = bcThumpicService.baGetSelectsearch(searMap);
						}
				    
					//封装数据将传到前台数据
					 m.addAttribute("datas",searchList);//查询出的数据
					 m.addAttribute("pageCount",pageCount);//一个分多少页
					 m.addAttribute("currentPage", currentPage);//当前页数
					 m.addAttribute("rowCount", rowCount);//一共多少条数据
					 m.addAttribute("pageSize", pageSize);//每页显示的条数
					 m.addAttribute("colourType", colour);//颜色标示
					 m.addAttribute("PicUrl", PicUrl);//图片服务器的地址
					 m.addAttribute("queryValue", parKeyword);//获取到的查询值
					 
					//以下计算开始显示的页码和结束显示的页码
						int showCount = 10;  //页面显示多少个页码
						int showStart = 0;   //
						int showEnd = 0;     //
						//如果总页码还不够15页
						if(pageCount<=showCount){
							showStart=1;
							showEnd=pageCount;//那么结束页面就等于总页码
						}else{//分页显示页码
							if(currentPage<=(showCount/2)){
								showStart=1;
								showEnd=showCount;
							}else{
								showStart=currentPage-(showCount/2-1);
								showEnd=showStart+(showCount-1);
							}
							//如果showEnd已经超出总页面
							if(showEnd>=pageCount){ //最后的页面大于等于总页码
								showEnd=pageCount;
								showStart=showEnd-(showCount-1);
							}
						}
						m.addAttribute("showStart",showStart);
						m.addAttribute("showEnd",showEnd);
				}catch(Exception e){
					throw new RuntimeException(e);
				}
	}
	//批量新增类型数据
	@RequestMapping("/batchSave.do")
	public void batchSave(HttpServletRequest request, HttpServletResponse response,Model m) throws IOException{
		String radio = request.getParameter("radioval");//获取单选
		String colour=("col".equals(radio))?"1":"0";
		
		bcThumpicService.clearThumPicData(colour);//先清空数据在保存数据
		
		StringBuffer buffer=new StringBuffer();//存储重复名称数据
		StringBuffer ZNName=new StringBuffer();//存储名称中出现中文的信息
		StringBuffer abnormal = new StringBuffer();// 异常数据
		
		String textarea = request.getParameter("textarea").trim();//获取文本域数据
		String[] splits = textarea.split("#");//切割数据
		//中文返回的编码
		response.setContentType("text/html"); 
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		for(int x=0;x<splits.length;x++){
			boolean deposit=true;//用来判断数据是否要保存的
			String[] splitSon = splits[x].split("\\|");
			String name = splitSon[0].trim();
			//如果大于三个或者小于2的时候表示就有异常
			if(splitSon.length>3||splitSon.length<2){
				if (abnormal.length() > 0) {
					abnormal.append("," + name);
				} else {
					abnormal.append(name);
				}
				continue;  
			}
			Map<String,Object> map=new HashMap<String,Object>();
			 map.put("picname",name);
			 map.put("colour",colour);
	    	 String selectNamecol = bcThumpicService.checkoutName(map);
	    	 if(null!=selectNamecol&&!"".equals(selectNamecol)){
	    		 deposit=false;
	    		if(buffer.length()>0){
	    			buffer.append(","+name);
	    		}else{
	    			buffer.append(name);
	    		} 
	    	 }	
	    	 //监测中文
			 boolean variable=true;
			   for(int i=0;i<name.length();i++){  
		    		 boolean matches = name.substring(i,i+1).matches("[\\u4e00-\\u9fa5]+");//监测是否有中文
		    		 if(matches){
		    			 variable=false;
		    			 deposit=false;
		    			 break;  
		    		 }
		    	  }
	    	 if(!variable){
	    		 if(ZNName.length()>0){
	    			 ZNName.append(","+name);
		    		}else{
					ZNName.append(name);
		    		} 
	    	 }
	    	 if(deposit){
	    	 BcThumpic recObject= bcThumpicService.reciprocalOne(colour);//获取最后一条数据的对象值
				/*int cacheOrder=recObject.getFeatureSort();//缓存排序*/
				int cacheOrder=(null==recObject?0:recObject.getFeatureSort());
						BcThumpic bcThumpic = new BcThumpic();
							bcThumpic.setId(UUIDUtils.getUUID32());
							bcThumpic.setPicname(name);
							bcThumpic.setDesctibe(splitSon[1]);
							bcThumpic.setColour(colour);
							bcThumpic.setUrladdress("/thumb/"+radio+"/"+splitSon[0].trim()+".jpg");
							bcThumpic.setIsRecommend("0");
							if(splitSon.length>2){//如果有排序值就使用自己的
								try{
									bcThumpic.setFeatureSort(Integer.parseInt(splitSon[2]));
								}catch (Exception e) {
									e.printStackTrace();
									if (abnormal.length() > 0) {
										abnormal.append("," + name);
									} else {
										abnormal.append(name);
									}
									continue;  
								}
								
								//当使用自己的排序值的时候也需要查询一遍
								recObject= bcThumpicService.reciprocalOne(colour);//获取最后一条数据的对象值
								cacheOrder=recObject.getFeatureSort();
							}else{
								cacheOrder=cacheOrder+10;
								bcThumpic.setFeatureSort(cacheOrder);	
							}
							
						bcThumpicService.addInsert(bcThumpic);
	    	 }
		}
		//当大于0的时候表示有重复的
		if(buffer.length()>0||ZNName.length()>0||abnormal.length()>0){
			out.print(buffer+"_"+ZNName+"_"+abnormal);
			/*m.addAttribute("returnVal",buffer);*/ 
		}else{
			out.print("success");
		}
	}		
	
/*	//备份数据
	@RequestMapping("/backupsDate.do")
	public void backupsDate(HttpServletRequest request, HttpServletResponse response,Model m) throws IOException{
		String dbdir = variableService.selectVariable("dbdir");
    	String dbname = variableService.selectVariable("dbname");
    	String backdir = variableService.selectVariable("backdir");
		JaxWsDynamicClientFactory backupsdcf= JaxWsDynamicClientFactory.newInstance();
		String dbPath = variableService.selectVariable("WS_WSDLMonitor");
		Client createClient = backupsdcf.createClient(dbPath);
		String object = null;
		try {
			Object[] invoke = createClient.invoke("backupsDate",dbdir,dbname,backdir);
			object =(String)invoke[0];
		} catch (Exception e) {
			e.printStackTrace();
			object = "erro";
		}
		response.getWriter().print(object);
	} */ 
	
	/** 
	    * 备份数据 
	    * @param dbdir mysql数据库安装路径 
	    * @param dbname  数据库的名称 
	    * @param backdir 备份的目录 
	  */ 
	@RequestMapping("/backupsDate.do")
	public void backupsDate(HttpServletRequest request, HttpServletResponse response,Model m) throws IOException{
		String dbdir = variableService.selectVariable("dbdir");
    	String dbname = variableService.selectVariable("dbname");
    	String backdir = variableService.selectVariable("backdir");
    	String object=backupsDate(dbdir,dbname,backdir);
		response.getWriter().print(object);
	} 
	
	public String backupsDate(String dbdir, String dbname, String backdir) {
		 Calendar calendar = Calendar.getInstance();  
	        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HHmmss");  
	        String currentTime = dateFormat.format(calendar.getTime()); 
	        String 	returndate;
	        try {  
	            long startTime = System.currentTimeMillis();  
	            Runtime rt = Runtime.getRuntime();
	            //输入数据的账号密码对数据的当前数据进行备份
	            Process child = rt.exec(dbdir + "/bin/mysqldump --default-character-set=utf8 -uroot -p48512 "+ dbname);  
	            InputStream in = child.getInputStream();  
	            InputStreamReader xx = new InputStreamReader(in, "utf8");  
	  
	            FileOutputStream fout = new FileOutputStream(new File(backdir, dbname + "_" + currentTime + ".sql"));  
	            OutputStreamWriter writer = new OutputStreamWriter(fout, "utf8");  
	  
	            dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
	  
	            writer.write("-- Dump by Microsoul at " + dateFormat.format(calendar.getTime()) + "\r\n");  
	  
	            String inStr;  
	            BufferedReader br = new BufferedReader(xx);  
	            // 这样实时写入文件很重要，网上有很多是将读取的存入字符串中，最后再写成文件，这样会导致Java的堆栈内存溢出。  
	            while ((inStr = br.readLine()) != null) {  
	                writer.write(inStr);  
	                writer.write("\r\n");  
	            }  
	  
	            writer.write("\r\n-- Use " + (System.currentTimeMillis() - startTime) + "ms\r\n");  
	     
	            writer.flush();  
	            in.close();  
	            xx.close();  
	            br.close();  
	            writer.close();  
	            fout.close();  
	            returndate="succeed";
	        } catch (Exception e) {  
	            PrintStream print = null;  
	            try {  
	                print = new PrintStream(new File(backdir, currentTime + "_backup_err.log"));  
	                dateFormat.applyPattern("yyyy-MM-dd HH:mm:ss");  
	                currentTime = dateFormat.format(calendar.getTime());  
	                print.println(currentTime + "  backup failed.");  
	                e.printStackTrace(print);  
	                print.flush();  
	            } catch (IOException e2) {  
	  
	            } finally {  
	                if (print != null) {  
	                    print.close();  
	                }  
	            }  
	            returndate="erro";
	        } 
		return returndate;
	}
	
	
	/**
	 *略缩图数据回显
     * @throws IOException 
	 */
	@RequestMapping("/returnThumBatch.do")
	    public @ResponseBody List<BcThumpic> returnThumBatch(String radioval){
		radioval="col".equals(radioval)?"1":"0";
	         List<BcThumpic> cs = bcThumpicService.selectHomepage(radioval);
	        return cs;
	   }
	
	/**
	 *清空数据
     * @throws IOException 
	 */
	@RequestMapping("/clearData.do")
	public void clearData(HttpServletRequest request,HttpServletResponse response,Model m,String colour) throws IOException{
		int clearData = bcThumpicService.clearThumPicData(colour);
		response.getWriter().print(clearData);
	}
	
	//首页生成静态页面这里这个是给修改底部链接使用的
		public String homePage(HttpServletRequest request, HttpServletResponse response){
			String PackPath = variableService.selectVariable("PACKGE_TEMPLATE");//模板地址
			String portUrl = variableService.selectVariable("port_url"); //D:/ruanjian/tomcat/apache-tomcat-7.0.26/wtpwebapps/pc-portal
			String variable=variableService.selectVariable("PIC_URL");
			String variableYear=variableService.selectVariable("year");//最新年份
			String staticYear=variableService.selectVariable("picStatic_Year");//图纸开始年份
			String porUrl=variableService.selectVariable("POR_URL");//静态页面磁盘映射
			
			//将年份转换为int类型
			int i=Integer.parseInt(staticYear);
			int n=Integer.parseInt(variableYear);
			 List<String> list=new ArrayList<String>();
		for (int year= i; year <= n;year++) {
				Collections.reverse(list);//强数据反转
				if(2012!=year){
					list.add(String.valueOf(year-1));
					Collections.reverse(list);//强数据反转
				}
			}
			
			
			Map<String,Object> allMap=new HashMap<String,Object>();
				 Map<String, Object> playMap = new HashMap<String,Object>();
				 playMap.put("year",variableYear);
				//查询首页轮播图的地址
				List<Map<String, Object>> playArrayList = bcThumpicService.getSelectRecommend(playMap);
				allMap.put("nextYear", String.valueOf(Integer.parseInt(variableYear)+1));
				allMap.put("url",variable);
				allMap.put("year",variableYear);
				allMap.put("moveList",playArrayList);
				allMap.put("porUrl",porUrl);
				allMap.put("yearList", list);// 年份集合
			//查询友情链接类型参数1表示类型
			List<BcLinktype> selectByFriendship = bcLinktypeService.selectByFriendship("1");
			List<Map<String, Object>> arrayList = new ArrayList<Map<String, Object>>();
			 for(BcLinktype tmp:selectByFriendship){
				 Map<String,Object> map=new HashMap<String,Object>();
				//通过类型id查询出对应的链接信息
				 List<BcLinktble> selectByLink = bcLinktbleService.selectByLink(tmp.getId());
				 map.put("LinkKey",tmp.getLinkTypename());
				 map.put("LinkVal",selectByLink);
				 arrayList.add(map);
		        }
			 allMap.put("arrayList",arrayList);
			 
			 String var="success";
				FMutil fMutil = new FMutil();
						//生成静态页面。如名称相同覆盖
						try {
							fMutil.ouputLinkFile("index.ftl","lookFour.html", allMap,"/index.html",PackPath,portUrl);
						} catch (Exception e) {
							var="erro";
							e.printStackTrace();
						}
			return var;
		}
	
}
